import { PageContainer } from '@ant-design/pro-layout';
import { Button, message, Popconfirm, Form } from 'antd';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm, ProFormText, ProFormSelect, ProFormUploadDragger, ModalForm, ProFormTextArea, ProFormDatePicker } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PlusOutlined, FileExcelOutlined } from '@ant-design/icons';
import { Customer, TreeData } from '../../../model';
import { Cascader } from 'antd';
import { hospitalData, areaTwo, saveHospital, updateHospital, deleteHospital, exportHospital } from '../service';
import { Spin } from 'antd';
import { exportFile } from '@/utils/utils';
import CustomerAuth from '@/components/Common/CustomerAuth';
export default (() => {
  async function requestAreas() {
    var val = await areaTwo();

    if (val.errorCode === '200') {
      val.data.forEach((element: any) => {
        element.value = element.label;
        element.children.forEach((sub: any) => {
          sub.value = sub.label;
        });
      });
      setAreas(val.data);
    }
  }

  React.useEffect(() => {
    requestAreas();
    return function cleanup() {};
  }, []);
  const [spinningFlag, setSpinningFlag] = useState(false);
  const [showCreate, setShowCreate] = useState(false);
  const [editModel, setEditModel] = useState<any>();
  const [showImport, setShowImport] = useState<boolean>(false);
  const [areas, setAreas] = useState<TreeData[]>();
  const [fullArea, setFullArea] = useState<string[]>();
  const actionRef = useRef<ActionType>();
  const authRef = useRef<any>();

  const handleDelete = async (id: string) => {
    var val = await deleteHospital({
      ids: id,
      mails: 'jhuang@strokemedical.com,jycong@strokemedical.com,chenbingbing_123@163.com,lphe@strokemedical.com'
    });

    if (val.errorCode === '200') {
      message.success('删除成功');
      actionRef.current?.reloadAndRest?.();
    } else {
      message.error(val.errorMessage);
    }
  }; //表头信息以及表值设置


  const columns: ProColumns<Customer>[] = [{
    title: '医院代码',
    dataIndex: 'bh',
    width: 100
  }, {
    title: '医院名称',
    ellipsis: true,
    width:200,
    dataIndex: 'name'
  },{
    title: '上级医院',
    ellipsis: true,
    width:200,
    dataIndex: 'upper'
  }, {
    title: '医院类型',
    dataIndex: 'cusType',
    valueType: 'select',
    width: 100,
    valueEnum: {
      公立医院: {
        text: '公立医院'
      },
      私立医院: {
        text: '私立医院'
      },
      军区医院: {
        text: '军区医院'
      },
      卫生院: {
        text: '卫生院'
      },
      社区卫生服务中心: {
        text: '社区卫生服务中心(站)'
      },
      诊所: {
        text: '诊所(卫生所、医务室、护理站)'
      }
    }
  }, {
    title: '地区',
    dataIndex: 'city',
    ellipsis: true,
    valueType: 'select',
    width: 100,
    hideInSearch: true,
    renderText: (_, record: Customer) => `${record.provinces}/${record.city}`
  }, {
    title: '级别/等级',
    dataIndex: 'level',
    width: 80,
    ellipsis:true,
    hideInSearch: true,
    renderText: (_, record: Customer) => `${record.level}/${record.grade}`
  }, {
    title: '开发入院',
    dataIndex: 'admission_type',
    width: 80,
    hideInSearch: true,
    renderText: (_, record: any) => {
      if (record.admission_type) {
        return record.admission_type === '1' ? '是' : '否';
      }

      return '';
    }
  }, {
    title: '首次开发日期',
    dataIndex: 'admission_time',
    width: 100,
    hideInSearch: true
  }, {
    title: '地址',
    dataIndex: 'address',
    width: 150,
    ellipsis: true,
    hideInSearch: true
  },{
    title: '网址',
    dataIndex: 'website',
    width: 150,
    ellipsis: true,
    hideInSearch: true
  }, {
    title: '操作',
    fixed:'right',
    width: 150,
    // hideInTable: sessionStorage.getItem('access')!='admin',
    valueType: 'option',
    render: (text, record: any, _, action) => [<a key='dealer' onClick={async () => {
      authRef.current.showAuth(record.id);
    }} >授权</a>, <a key='editable' onClick={() => {
      record.areas = [record.provinces, record.city];
      setFullArea([record.provinces, record.city]);
      setEditModel(record);
      setShowCreate(true);
    }} >
          编辑
        </a>, <Popconfirm title='确定删除该医院吗?' key='delete' onConfirm={() => handleDelete(record.id)} >
          <a>删除</a>
        </Popconfirm>]
  }];

  function onFileUpload(info: any) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }

    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功，后台正在处理...`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  }

  function onChange(info: any, label: any) {
    if (label.length > 1) {
      setFullArea([label[0].label, label[1].label]);
    } else {
      setFullArea([label[0].label]);
    }
  }

  const formRef = useRef();
  return <PageContainer>
    <ProTable<Customer> scroll={{x:1300}} actionRef={actionRef} headerTitle='医院列表' request={(params, sorter, filter) => {
      if (params.cusType) {
        if (params.cusType === '诊所') {
          params.cusType = '诊所(卫生所、医务室、护理站)';
        } else if (params.cusType === '社区卫生服务中心') {
          params.cusType = '社区卫生服务中心(站)';
        }
      }
      params.category=1
      params.name = '上海交通大学'
      return hospitalData({ ...params,
        filter
      });
    }} columns={columns} rowKey='id' pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} toolBarRender={() => [<Button type='primary' key='primary' // hidden ={sessionStorage.getItem('access')!='admin'}
    onClick={() => {
      setFullArea([]);
      setEditModel(undefined);
      setShowCreate(true);
    }}>
          <PlusOutlined/>新建
        </Button>, <Button type='primary' key='primary' onClick={async () => {
      setSpinningFlag(true);
      var val = await exportHospital();

      if (val.errorCode === '200') {
        exportFile(val.data, '医院.xlsx');
      } else {
        message.error('导出失败');
      }

      setSpinningFlag(false);
    }}>
      <FileExcelOutlined/>导出
     </Button>]} toolbar={{
      settings: []
    }} search={{
      span: 5
    }}/>
         <ModalForm onVisibleChange={setShowImport} visible={showImport} modalProps={{
      destroyOnClose: true,
      forceRender: true
    }} onFinish={async (values: any) => {
      console.log(values);
      return true;
    }}>
             <div style={{
        margin: '10px 0'
      }}><Button type='primary'> <FileExcelOutlined/>EXCEL模板下载</Button></div>
            <ProFormUploadDragger label='选择excel上传医院信息' name='file' action='upload.do' max={1} onChange={onFileUpload}/>
         </ModalForm>
         <DrawerForm title={editModel ? '医院编辑' : '医院新增'} onVisibleChange={setShowCreate} visible={showCreate} formRef={formRef} drawerProps={{
      destroyOnClose: true
    }} onFinish={async (values: any) => {
      var val;
      values.provinces = fullArea?.[0];
      values.city = fullArea?.[1];

      if (values.admission_time == undefined) {
        values.admission_time = '';
      }

      if (editModel) {
        values.id = editModel.id;
        val = await updateHospital(values);
      } else {
        val = await saveHospital(values);
      }

      if (val.errorCode === '200') {
        message.success('提交成功');
        actionRef.current?.reloadAndRest?.();
        return true;
      } else {
        message.error(val.errorMessage);
        return false;
      }
    }}>
           <ProForm.Group>
              <ProFormText name='name' label='医院名称(中文)' placeholder='请输入医院中文名称' width='md' initialValue={editModel?.name} rules={[{
          required: true
        }]}/>
              <ProFormText name='cusENName' label='医院名称(英文)' placeholder='请输入医院英文名称' initialValue={editModel?.cusENName} width='md' data-inspector-line='280'/>
           </ProForm.Group>
           
           <ProForm.Group>
              <ProFormText name='cusSubName' label='医院别名(中文)' placeholder='请输入医院中文别名名称' width='md' initialValue={editModel?.cusSubName} />
              <ProFormText name='cusENSubName' label='医院别名(英文)' placeholder='请输入医院英文别名名称' width='md' initialValue={editModel?.cusENSubName}/>
           </ProForm.Group>
            <ProForm.Group>
            <ProFormText name='zipCode' label='邮政编码' placeholder='请输入邮政编码' initialValue={editModel?.zipCode} width='md'/>
            <Form.Item style={{
          width: '330px'
        }} name='areas' initialValue={editModel?.areas} label='地区' rules={[{
          required: true
        }]}>
              <Cascader options={areas} placeholder='请选择' onChange={onChange}/>
          </Form.Item>
          </ProForm.Group>
          <ProFormText name='website' label='官网地址' placeholder='请输入官网地址' width='lg'/>

          <ProFormText name='address' label='详细地址' placeholder='请输入地址' width='lg' initialValue={editModel?.address}/>
          <ProForm.Group>
              <ProFormSelect name='cusType' label='医院类型' placeholder='请选择医院类型' width='md' initialValue={editModel?.cusType} rules={[{
          required: true
        }]} options={[{
          value: '公立医院',
          label: '公立医院'
        }, {
          value: '私立医院',
          label: '私立医院'
        }, {
          value: '军区医院',
          label: '军区医院'
        }, {
          value: '卫生院',
          label: '卫生院'
        }, {
          value: '社区卫生服务中心(站)',
          label: '社区卫生服务中心(站)'
        }, {
          value: '诊所(卫生所、医务室、护理站) ',
          label: '诊所(卫生所、医务室、护理站) '
        }]}/>
              <ProFormSelect name='level' label='医院级别' placeholder='请选择医院类型' allowClear={false} width='xs' initialValue={editModel?.level} rules={[{
          required: true
        }]} options={[{
          value: '三级',
          label: '三级'
        }, {
          value: '二级',
          label: '二级'
        }, {
          value: '一级',
          label: '一级'
        }, {
          value: '未评级',
          label: '未评级'
        }]}/>
                <ProFormSelect name='grade' label='医院等级' placeholder='请选择医院类型' width='xs' allowClear={false} initialValue={editModel?.grade} rules={[{
          required: true
        }]} options={[{
          value: '甲等',
          label: '甲等'
        }, {
          value: '乙等',
          label: '乙等'
        }, {
          value: '丙等',
          label: '丙等'
        }, {
          value: '未评等',
          label: '未评等'
        }]}/>
          </ProForm.Group>
          <ProForm.Group >
            <ProFormSelect name='admission_type' label='是否开发入院' placeholder='请选择' width='xs' initialValue={editModel?.admission_type} options={[{
          value: '1',
          label: '是'
        }, {
          value: '2',
          label: '否'
        }]}/>
              <ProFormDatePicker name='admission_time' label='首次开发入院日期' placeholder='请选择' width='sm' initialValue={editModel?.admission_time === '' ? undefined : editModel?.admission_time}/>
          </ProForm.Group>
          <ProFormTextArea name='remarks' label='备注' placeholder='请输入备注' fieldProps={{
        showCount: true,
        maxLength: 200
      }} initialValue={editModel?.remarks}>
          </ProFormTextArea>

          {/* 添加科室医生联系人 */}
         </DrawerForm>
         <CustomerAuth ref={authRef}/>
         <Spin spinning={spinningFlag} style={{
      transform: 'translate(-50%,-50%)',
      left: '50%',
      top: '50%',
      position: 'absolute'
    }}/>
  </PageContainer>;
});